package avicit.bdp.dms.approval.service;

import avicit.bdp.common.base.BaseService;

import avicit.bdp.common.dto.approval.ApprovalDTO;
import avicit.bdp.dms.approval.dao.ApprovalHistoryDAO;
import avicit.bdp.dms.approval.dto.ApprovalHistoryDTO;
import avicit.bdp.core.enums.ApprovalState;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.properties.PlatformConstant;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-06-20
 * @类说明：ApprovalHistoryService
 * @修改记录：
 * @注意事项：
 * @主要功能：审批中心历史记录Service
 */
@Service
public class ApprovalHistoryService extends BaseService<ApprovalHistoryDAO, ApprovalHistoryDTO> {
    private static final Logger logger = LoggerFactory.getLogger(ApprovalHistoryService.class);

    @Autowired
    private ConvertColumnClient convertColumnClient;

    /**
     * 根据审批ID查询历史记录
     * @param approvalId
     * @return
     */
    public List<ApprovalHistoryDTO> getApprovalHistoryList(String approvalId) {
        if (StringUtils.isBlank(approvalId)) {
            return new ArrayList<>();
        }

        List<ApprovalHistoryDTO> result = this.mapper.getApprovalHistoryList(approvalId);
        if (CollectionUtils.isEmpty(result)) {
            return new ArrayList<>();
        }
        valueConvert(result);

        return result;
    }

    /**
     * 删除审批历史记录
     * @param approvalId
     * @return
     */
    public Integer deleteApprovalHistoryByCond(String approvalId) {
        if (StringUtils.isBlank(approvalId)) {
            return 0;
        }

        return this.mapper.deleteApprovalHistoryByCond(approvalId);
    }

    /**
     * 批量插入申请/重新申请历史记录
     * @param applyList 申请列表
     * @param isReapply 是否为重新申请，true：是、false：否
     * @return
     */
    public boolean batchInsertApplyHistory(List<ApprovalDTO> applyList, boolean isReapply) {
        if (CollectionUtils.isEmpty(applyList)) {
            return true;
        }

        List<ApprovalHistoryDTO> historyList = new ArrayList<>();
        for (ApprovalDTO apply : applyList) {
            if (apply == null) {
                continue;
            }

            ApprovalHistoryDTO history = new ApprovalHistoryDTO();
            history.setId(ComUtil.getId());
            history.setApprovalId(apply.getId());

            String submitUserId = apply.getSubmitUserId();
            List<String> nameList = getUserNamesByIds(Arrays.asList(submitUserId));
            if (CollectionUtils.isNotEmpty(nameList)) {
                if (isReapply) {
                    history.setContent(String.format("【%s】重新发起申请.", nameList.get(0)));
                } else {
                    history.setContent(String.format("【%s】发起申请.", nameList.get(0)));
                }
            }
            history.setState(ApprovalState.APPROVAL.getCode());

            PojoUtil.setSysProperties(history, PlatformConstant.OpType.insert);

            historyList.add(history);
        }

        // 批量新增审批
        return this.batchInsertHistory(historyList);
    }

    /**
     * 批量插入撤回历史记录
     * @param applyList
     * @return
     */
    public boolean batchInsertRevokeHistory(List<ApprovalDTO> applyList) {
        if (CollectionUtils.isEmpty(applyList)) {
            return true;
        }

        List<ApprovalHistoryDTO> historyList = new ArrayList<>();
        for (ApprovalDTO apply : applyList) {
            if (apply == null) {
                continue;
            }
            if (StringUtils.isEmpty(apply.getId())) {
                continue;
            }
            if (apply.getState() == null) {
                continue;
            }

            ApprovalHistoryDTO history = new ApprovalHistoryDTO();
            history.setId(ComUtil.getId());
            history.setApprovalId(apply.getId());
            history.setState(apply.getState());

            String loginUserId = apply.getSubmitUserId();
            List<String> nameList = getUserNamesByIds(Arrays.asList(loginUserId));
            history.setContent(String.format("【%s】撤回申请.", nameList.get(0)));

            PojoUtil.setSysProperties(history, PlatformConstant.OpType.insert);

            historyList.add(history);
        }

        // 批量新增审批
        return this.batchInsertHistory(historyList);
    }

    /**
     * 批量插入处理历史记录
     * @param applyList
     * @return
     */
    public boolean batchInsertProcessHistory(List<ApprovalDTO> applyList) {
        if (CollectionUtils.isEmpty(applyList)) {
            return true;
        }

        List<ApprovalHistoryDTO> historyList = new ArrayList<>();
        for (ApprovalDTO apply : applyList) {
            if (apply == null) {
                continue;
            }
            if (StringUtils.isEmpty(apply.getId())) {
                continue;
            }
            if (apply.getState() == null) {
                continue;
            }

            ApprovalHistoryDTO history = new ApprovalHistoryDTO();
            history.setId(ComUtil.getId());
            history.setApprovalId(apply.getId());
            history.setState(apply.getState());

            String loginUserId = ThreadContextHelper.getUserId() == null ? "1" : ThreadContextHelper.getUserId();
            List<String> nameList = getUserNamesByIds(Arrays.asList(loginUserId));
            if (CollectionUtils.isNotEmpty(nameList)) {
                if (ApprovalState.ACCESS.getCode() == apply.getState()) {
                    history.setContent(String.format("【%s】审批通过.", nameList.get(0)));
                } else if (ApprovalState.REJECT.getCode() == apply.getState()) {
                    history.setContent(String.format("【%s】驳回申请.", nameList.get(0)));
                }
            }

            PojoUtil.setSysProperties(history, PlatformConstant.OpType.insert);

            historyList.add(history);
        }

        // 批量新增审批
        return this.batchInsertHistory(historyList);
    }

    /**
     * 批量插入历史记录
     * @param historyList 申请历史记录列表
     * @return
     */
    private boolean batchInsertHistory(List<ApprovalHistoryDTO> historyList) {
        if (CollectionUtils.isEmpty(historyList)) {
            return true;
        }

        return this.mapper.batchInsertApprovalHistory(historyList);
    }

    /**
     * 根据用户ID获取用户名
     * @param userIdList
     * @return
     */
    private List<String> getUserNamesByIds(List<String> userIdList) {
        if (CollectionUtils.isEmpty(userIdList)) {
            return new ArrayList<>();
        }

        List<String> userNameList = new ArrayList<>();
        // 设置创建者名称
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (String userId : userIdList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, userId);
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (String userId : userIdList) {
                userNameList.add(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, userId));
            }

//            /*******************打桩代码**************************/
//            for (String userId : userIdList) {
//                if (userId.equals("1")) {
//                    userNameList.add("平台管理员");
//                }
//            }
//            /*******************打桩代码**************************/
        }

        return userNameList;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     * @param dtoList
     */
    private void valueConvert(List<ApprovalHistoryDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }

        // 设置枚举类型
        for (ApprovalHistoryDTO dto : dtoList) {
            if (dto.getState() != null) {
                dto.setStateName(ApprovalState.getDescByCode(dto.getState()));
            }
        }
    }
}
